package br.ufc.pet.util;

import java.io.ByteArrayOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import br.ufc.pet.model.Usuario;

public class ReportUtil {

	private static final String USER = "postgres";
	private static final String PASS = "postgres";
	private static final String URL = "jdbc:postgresql://localhost:5432/flisol";
	
	public static byte[] geraCertificado(Usuario usuario, String path)throws SQLException, JRException{
		
		JasperDesign design = JRXmlLoader.load(path);

		JasperReport report = JasperCompileManager.compileReport(design);

		Connection con = DriverManager.getConnection(URL, USER, PASS);
		String sql = "select * from credenciados where codigo = ?";
		PreparedStatement stmt = con
				.prepareStatement(sql);

		stmt.setString(1, usuario.getCodigo());

		ResultSet rs = stmt.executeQuery();

		JRDataSource data = new JRResultSetDataSource(rs);

		Map<String, Object> map = new HashMap<String, Object>();

		JasperPrint print = JasperFillManager.fillReport(report, map, data);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		JRPdfExporter exporter = new JRPdfExporter();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);

		exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);

		exporter.exportReport();

		byte[] bytes = baos.toByteArray();

		con.close();
		return bytes;
		
	}
	
}
